
#include "EspMQTTClient.h"
#include "Adafruit_Sensor.h"
#include "Adafruit_AM2320.h"
Adafruit_AM2320 am2320 = Adafruit_AM2320();
#include "font.h"
#include "SSD1306Brzo.h"
#include <Wire.h>               // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h"        // legacy: #include "SSD1306.h"
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRsend.h>
#include <ir_Gree.h>
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
// Initialize the OLED display using brzo_i2c:
SSD1306Brzo display(0x3c, D3, D5);  // ADDRESS, SDA, SCL
const uint16_t kIrLed = 12;  // ESP8266 GPIO pin to use. Recommended: 12 (D6).
IRGreeAC ac(kIrLed);  // Set the GPIO to be used for sending messages.

String str = "esp-" + String(ESP.getFlashChipId());
char* HWID= (char*)str.c_str(); 

EspMQTTClient client(
  "wifi-ssid",
  "wifi-pwd",
  "0.0.0.0",  // MQTT Broker server ip
  "mqtt-user",   // Can be omitted if not needed
  "mqtt-pwd",   // Can be omitted if not needed
  HWID,     // Client name that uniquely identify your device
  1883              // The MQTT port, default to 1883. this line can be omitted
);

void setup()
{
  ac.begin();
  Serial.begin(115200);
  while (!Serial) {
    delay(10); // hang out until serial port opens
  }
  // Optionnal functionnalities of EspMQTTClient : 
  client.enableDebuggingMessages(); // Enable debugging messages sent to serial output
  client.enableHTTPWebUpdater(); // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password").
  client.enableLastWillMessage("HomeClient/lastwill", "I am going offline");  // You can activate the retain flag by setting the third parameter to true
  Serial.println("AM2320 Ready");
  am2320.begin();
  display.init();

  display.flipScreenVertically();
  display.setFont(Coming_Soon_Regular_24);//ArialMT_Plain_10
}

void drawTandH(float hum, float temp) {
    // Font Demo1
    // create more fonts at http://oleddisplay.squix.ch/
    String str_temp = String(temp);
    String str_hum = String(hum);
    str_temp = str_temp.substring(0,str_temp.length()-1);
    str_hum = str_hum.substring(0,str_hum.length()-1);
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(Coming_Soon_Regular_24);
    display.drawString(0, 0, str_temp + "ºC");
    display.setFont(Coming_Soon_Regular_24);
    display.drawString(64, 24, str_hum + "%");
    //display.setFont(ArialMT_Plain_16);
    //display.drawString(0, 48, "Hello world");
}

void GreeAC_On_26(){
  ac.on();
  ac.setFan(1);
  // kGreeAuto, kGreeDry, kGreeCool, kGreeFan, kGreeHeat
  ac.setMode(kGreeCool);
  ac.setTemp(26);  // 16-30C
  ac.setSwingVertical(true, kGreeSwingAuto);
  ac.setXFan(false);
  ac.setLight(false);
  ac.setSleep(false);
  ac.setTurbo(false);
  ac.send();
}

void GreeAC_Off(){
  ac.off();
  ac.setFan(1);
  // kGreeAuto, kGreeDry, kGreeCool, kGreeFan, kGreeHeat
  ac.setMode(kGreeCool);
  ac.setTemp(26);  // 16-30C
  ac.setSwingVertical(true, kGreeSwingAuto);
  ac.setXFan(false);
  ac.setLight(false);
  ac.setSleep(false);
  ac.setTurbo(false);
  ac.send();
}

// This function is called once everything is connected (Wifi and MQTT)
// WARNING : YOU MUST IMPLEMENT IT IF YOU USE EspMQTTClient
void onConnectionEstablished()
{
  // Subscribe to "mytopic/test" and display received message to Serial
  client.subscribe("home/ctrl", [](const String & payload) {
    if(payload == "GreeAC_On_26"){
      GreeAC_On_26();
      Serial.println("AC_on sent!");
    }else if(payload == "GreeAC_Off"){
      GreeAC_Off();
      Serial.println("AC_off sent!");
    }
  });
  // Publish a message to "mytopic/test"
  //client.publish("mytopic/test", "Hello"); // You can activate the retain flag by setting the third parameter to true

}

void loop()
{
  float temp=0,tempc,hum=0,humc;
  int i=1;
  for(i=1;i<=5;i++){
    temp=temp+am2320.readTemperature();
    hum=hum+am2320.readHumidity();
    delay(2000);
  }
  tempc=am2320.readTemperature();
  humc=am2320.readHumidity();
  if(temp/5 - tempc<=0.5 && tempc - temp/5<=0.5){
    temp=tempc;
  }else{
    temp=temp/5;
  }
  if(hum/5 - humc<=1.5 && humc - hum/5<=1.5){
    hum=humc;
  }else{
    hum=hum/5;
  }
  client.publish("home/temp", String(temp));
  client.publish("home/hum", String(hum));
  display.clear();
  hum = am2320.readHumidity();
  temp = am2320.readTemperature();
  drawTandH(hum,temp);
  display.setTextAlignment(TEXT_ALIGN_RIGHT);
  display.drawString(10, 128, String(millis()));
  // write the buffer to the display
  display.display();
  delay(2000);
  client.loop();
}
